package com.ionehe.group.common.uaa.ex.domain.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.base.CaseFormat;
import com.ionehe.group.common.io.Response;
import com.ionehe.group.common.uaa.ex.application.converter.CustomerConverter;
import com.ionehe.group.common.uaa.ex.dao.CustomerInfoDao;
import com.ionehe.group.common.uaa.ex.dao.CustomerSetMealDao;
import com.ionehe.group.common.uaa.ex.dao.SetMealDao;
import com.ionehe.group.common.uaa.ex.domain.service.CustomerReadService;
import com.ionehe.group.common.uaa.ex.dto.CustomerInfoDTO;
import com.ionehe.group.common.uaa.ex.dto.CustomerInfoListDTO;
import com.ionehe.group.common.uaa.ex.dto.Paging;
import com.ionehe.group.common.uaa.ex.model.UaaCustomerInfo;
import com.ionehe.group.common.uaa.ex.model.UaaCustomerSetMeal;
import com.ionehe.group.common.uaa.ex.model.UaaSetMeal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Copyright (c) 2020 ionehe.com
 * Date: 2020/11/26 0026
 * Time: 15:02
 *
 * @author 2020年 <a href="mailto:a@ionehe.com">秀</a>
 */
@Service
@Slf4j
public class CustomerReadeServiceImpl implements CustomerReadService {

    @Autowired
    CustomerInfoDao customerInfoDao;
    @Autowired
    CustomerSetMealDao customerSetMealDao;
    @Autowired
    SetMealDao setMealDao;
    @Autowired
    CustomerConverter customerConverter;


    @Override
    public Response<Paging<CustomerInfoListDTO>> customerList(Integer pageNum, Integer pageSize, Map<String, Object> conditions,
                                                              String sortKey, String order) {
        // 查询客户信息列表
        List<CustomerInfoListDTO> customerInfoListDTOList = new ArrayList<>();

        Example e = new Example(UaaCustomerInfo.class);
        Example.Criteria cri = e.createCriteria()
                .andEqualTo("isDelete", false);

        if (StrUtil.isNotBlank(sortKey) && StrUtil.isNotBlank(order)) {
            e.setOrderByClause(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, sortKey) + " "+ order);
        }

        if (CollUtil.isNotEmpty(conditions)) {
            Object pid = conditions.get("pid");
            if (Objects.nonNull(pid)) {
                cri.andEqualTo("pid", pid);
                conditions.remove("pid");
            }
            Object type = conditions.get("type");
            if (Objects.nonNull(pid)) {
                cri.andEqualTo("type", type);
                conditions.remove("type");
            }
            Object createTimeStart = conditions.get("createTimeStart");
            Object createTimeEnd = conditions.get("createTimeEnd");
            if (Objects.nonNull(createTimeStart) && Objects.nonNull(createTimeEnd)) {
                cri.andBetween("createTime", createTimeStart, createTimeEnd);
                conditions.remove("createTimeStart");
                conditions.remove("createTimeEnd");
            }
            Object ratingTimeStart = conditions.get("ratingTimeStart");
            Object ratingTimeEnd = conditions.get("ratingTimeEnd");
            if (Objects.nonNull(ratingTimeStart) && Objects.nonNull(ratingTimeEnd)) {
                cri.andBetween("ratingTime", ratingTimeStart, ratingTimeEnd);
                conditions.remove("ratingTimeStart");
                conditions.remove("ratingTimeEnd");
            }
            Object creditRating = conditions.get("creditRating");
            if (Objects.nonNull(creditRating)) {
                cri.andEqualTo("creditRating", creditRating);
                conditions.remove("creditRating");
            }
            Object bank = conditions.get("bank");
            if (Objects.nonNull(bank)) {
                cri.andIsNotNull("creditRating");
                conditions.remove("bank");
            }
            conditions.forEach((k, v) -> cri.andLike(k, "%" + v + "%"));
        }

        Page<CustomerInfoListDTO> page = PageHelper.startPage(pageNum, pageSize);
        List<UaaCustomerInfo> customerInfos = customerInfoDao.selectByExample(e);
        log.info("CustomerReadeServiceImpl[]customerInfoSelect[]success!");
        for (UaaCustomerInfo customerInfo : customerInfos) {
            // 查看客户所关联的套餐信息
            List<UaaCustomerSetMeal> customerSetMeals = customerSetMealDao.selectCustomerInfoListDTO(customerInfo.getId());
            // 查询所有的套餐id，组装套餐
            List<Long> idList = new ArrayList<>();
            for (UaaCustomerSetMeal customerSetMeal : customerSetMeals) {
                idList.add(customerSetMeal.getSetMealId());
            }
            List<UaaSetMeal> setMealList = setMealDao.selectByIds(idList);
            Map<Long, UaaSetMeal> setMealMap = setMealList.stream().collect(Collectors.toMap(UaaSetMeal::getId, p -> p));
            log.info("CustomerReadeServiceImpl[]customerSetMealsSelect[]success!");
            if (CollUtil.isNotEmpty(setMealList)) {
                for (UaaCustomerSetMeal customerSetMeal : customerSetMeals) {
                    // 根据套餐id查询套餐名称
                    log.info("CustomerReadeServiceImpl[]SetMealsSelect[]success!");
                    CustomerInfoListDTO customerInfoListDTO = new CustomerInfoListDTO();
                    BeanUtil.copyProperties(customerInfo, customerInfoListDTO);
                    if (!CollectionUtils.isEmpty(setMealMap) && setMealMap.get(customerSetMeal.getSetMealId()) != null && !"永久".equals(setMealMap.get(customerSetMeal.getSetMealId()).getDuration())) {
                        customerInfoListDTO.setTimeout(customerSetMeal.getTimeout().getTime());
                    }
                    customerInfoListDTO.setSetMealName(setMealMap.get(customerSetMeal.getSetMealId()).getName());
                    customerInfoListDTO.setSetMealId(customerSetMeal.getSetMealId());
                    if (customerSetMeal.getTimeout().before(new Date())) {
                        customerInfoListDTO.setSetMealId(null);
                    }
                    customerInfoListDTOList.add(customerInfoListDTO);
                }
            }
        }

        Paging<CustomerInfoListDTO> paging = new Paging<>(page.getTotal(), customerInfoListDTOList);
        return Response.yes(paging);
    }

    @Override
    public Response<List<CustomerInfoDTO>> listByType(String type) {
        Example e = new Example(UaaCustomerInfo.class);
        e.createCriteria()
                .andEqualTo("isDelete", false)
                .andEqualTo("type", type);

        List<UaaCustomerInfo> customerInfos = customerInfoDao.selectByExample(e);

        return Response.yes(customerConverter.do2dto(customerInfos));
    }

    @Override
    public Response<CustomerInfoDTO> detail(Long id) {
        UaaCustomerInfo customer = customerInfoDao.selectByPrimaryKey(id);

        return Response.yes(customerConverter.do2dto(customer));
    }
}
